from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import wl_attractions
import json

@csrf_exempt
def add_attraction(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        attraction = wl_attractions.objects.create(
            name=data['name'],
            major_category=data['major_category'],
            minor_category=data['minor_category'],
            details=data['details']
        )
        return JsonResponse({'id': attraction.id, 'name': attraction.name}, status=201)
    return JsonResponse({'error': 'Invalid request'}, status=400)

def show_attraction(request):
    attractions = wl_attractions.objects.all().values()
    return JsonResponse(list(attractions), safe=False)

@csrf_exempt
def modify_attraction_info(request, attraction_id):
    attraction = get_object_or_404(wl_attractions, id=attraction_id)
    if request.method == 'PUT':
        data = json.loads(request.body)
        attraction.name = data['name']
        attraction.major_category = data['major_category']
        attraction.minor_category = data['minor_category']
        attraction.details = data['details']
        attraction.save()
        return JsonResponse({'id': attraction.id, 'name': attraction.name})
    return JsonResponse({'error': 'Invalid request'}, status=400)

@csrf_exempt
def delete_attraction(request, attraction_id):
    if request.method == 'DELETE':
        attraction = get_object_or_404(wl_attractions, id=attraction_id)
        attraction.delete()
        return JsonResponse({'message': 'Attraction deleted successfully'})
    return JsonResponse({'error': 'Invalid request'}, status=400)